package com.yenlien.traceyun.usercenter.controller.component;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.usercenter.dao.UserDao;
import com.yenlien.traceyun.usercenter.entity.User;
import com.yenlien.traceyun.usercenter.entity.UserObject;
import com.yenlien.traceyun.webase.controller.BaseController;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @BelongsPackage: com.yenlien.traceyun.usercenter.controller.component
 * @Author: ChenXi
 * @CreateTime: 2023/09/01  13:58
 * @Description: 定期同步用户数据
 * @Version: 1.0
 */
//@Component
public class SyncUser extends BaseController {

    @Autowired
    private UserDao userDao;

    @Value("${login.appid}")
    private String appId;

    @Value("${login.appsecret}")
    private String appSecret;

    /**
     * 每天同步一次用户数据
     * @param
     */
    @Transactional(rollbackFor = Exception.class)
    @Scheduled(cron = "0 0 0 * * ? *")
    public Object getUserData(){
        Map<String, Object> map = new HashMap<>();
        map.put("timestamp", "2023-10-14 10:59:11");  //查询2023-07-12 00:00:00到当前日期有过信息变更的数据，如果不传，就是全量.传了就是增量同步
//        map.put("delFlag",0);  //用户是否删除，删除标记（0：正常；1：删除；）
        Object data = map; //原始数据
        String dataBody = JSON.toJSONString(data);//此处采用fastjson转换为字符串，即提的待签名交数据
        String digestHex = SecureUtil.hmacSha1(appSecret)
                .digestHex(dataBody);
        String result = HttpRequest.post("http://182.132.59.143:8084/api/open/user/list?pageNum=1&pageSize=8573")
                .header("app_id",appId)
                .header("signature",digestHex)
                .body(dataBody, "application/json")
                .timeout(50000)
                .execute()
                .body();
        JSONObject jsonObject = JSONObject.parseObject(result);
        JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("list");
        List<UserObject> objectList = JSON.parseArray(jsonArray.toJSONString(), UserObject.class);
        //转换数据保存
        List<User> users = new ArrayList<>();
        for (UserObject userObject : objectList) {
            User user = new User();
            user.setId(userObject.getId());
            user.setName(userObject.getName());
            user.setUsername(userObject.getUserName());
            user.setEmail(userObject.getEmail());
            user.setPhone(userObject.getPhonenumber());
            user.setDepartmentId(userObject.getDeptId());
            user.setIdCard(userObject.getIdCard());
            user.setGender(userObject.getSex());
            user.setHeadImg(userObject.getAvatar());
            user.setUserType(user.verdictType(userObject.getUserType()));
            users.add(user);
        }
        try {
            userDao.saveAll(users);
            return success("保存成功");
        } catch (Exception e) {
            e.printStackTrace();
            return fail("保存用户数据失败");
        }
    }
}
